package com.zjx.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zjx.reggie.common.R;
import com.zjx.reggie.domain.User;
import com.zjx.reggie.service.UserService;
import com.zjx.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;


@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info(user.toString());
        //获取手机号
        String phone = user.getPhone();

        if (!StringUtils.isEmpty(phone)) {
            //生成随机4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //调用阿里云短信服务发送短信
            //需要将生成的验证码保存到seesion中
            session.setAttribute("phone", code);
            return R.success("验证码短信发送成功");
        }
        return R.error("验证码短信发送失败");
    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取手机号
        String phone = (String) map.get("phone");
        //获取验证码
        String code = map.get("code").toString();
        //从session中获得发送成功的验证码
        Object code1 =session.getAttribute("phone");
        if (!StringUtils.isEmpty(code1)&&code1.equals(code)){
            //能取出验证码，并且验证码相等，可以登录

            //判断该用户是否是新用户
            LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone,phone);
            User users = userService.getOne(lambdaQueryWrapper);
            if (users==null){
                 users=new User();
                users.setPhone(phone);
                userService.save(users);
            }
            session.setAttribute("user",users.getId());
           return R.success(users);
        }
        return  R.error("验证码有误");
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出成功");

    }

}
